package com.d2.pay.rest;

import com.d2.pay.utils.Helper;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.ResponseBody;

import org.apache.http.message.BasicNameValuePair;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
 * Auth: Alexander Lo
 * Date: 2020-03-23
 * Description:
 */
@RestController
public class OrderController {



    /**
     * ++++++++++ 标准模式 ++++++++++
     * 获取业务订单信息
     * @param req
     * @return
     */

    @PostMapping(value = "order.do")
    @ResponseBody
    public Map<String, Object> order(HttpServletRequest req){

        String payMode = "1";
        int payType = Integer.parseInt(req.getParameter("type"));
        String payAmount = req.getParameter("amount");

        Map<String, Object> payData = Helper.getOrderInfo(payMode, payType, payAmount);

        Map<String, Object> result = new HashMap<String, Object>();
        result.put("code", 200);
        result.put("content", payData);

        return result;
    }

    /**
     * ++++++++++ 自定义模式 ++++++++++
     * 生成业务订单信息 & 调用绿点支付接口 & 自定义收银台
     * @param req
     * @param rep
     * @throws IOException
     */
    @GetMapping(value = "/custom-handle.do")
    public void customHandle(HttpServletRequest req, HttpServletResponse rep) throws IOException{

        String payMode = "2";
        int payType = 1;
        String payAmount = "0.5";

        // 1. 获取订单信息
        Map<String, Object> payData = Helper.getOrderInfo(payMode, payType, payAmount);

        // 2. 构建绿点官方接口需要的参数
        List<NameValuePair> params = new ArrayList<NameValuePair>();

        params.add(new BasicNameValuePair("uid", payData.get("uid").toString()));
        params.add(new BasicNameValuePair("amount", payData.get("amount").toString()));
        params.add(new BasicNameValuePair("account", payData.get("account").toString()));
        params.add(new BasicNameValuePair("type", payData.get("type").toString()));
        params.add(new BasicNameValuePair("mode", payData.get("mode").toString()));
        params.add(new BasicNameValuePair("notifyurl", payData.get("notifyurl").toString()));
        params.add(new BasicNameValuePair("ordernum", payData.get("ordernum").toString()));
        params.add(new BasicNameValuePair("orderuid", payData.get("orderuid").toString()));
        params.add(new BasicNameValuePair("goodname", payData.get("goodname").toString()));
        params.add(new BasicNameValuePair("key", payData.get("key").toString()));

        // 3. 使用 apache httpclient 调用绿点官方接口，获取支付信息。
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost("https://www.greenyep.com/api/index");
        // 注意：上报数据的编码格式，请务必确保为 UTF-8
        httpPost.setEntity(new UrlEncodedFormEntity(params, Consts.UTF_8));

        // 4. 发起请求
        CloseableHttpResponse response = httpclient.execute(httpPost);

        // 5. 处理结果
        try {

            if(response.getStatusLine().getStatusCode() == 200) {
                HttpEntity entity = response.getEntity();
                String content = EntityUtils.toString(entity, "utf-8");

                // TODO: 这里获取到绿点返回的支付数据，如无异常，即可自定义收银台页面

                rep.setCharacterEncoding("UTF-8");
                rep.setContentType("text/html;charset = UTF-8");
                rep.getWriter().write("pay data:" + content);
            } else {
                rep.getWriter().write("network error.");
            }
        } finally {
            response.close();
            httpclient.close();
        }
    }


    @GetMapping("/")
    public String test(){

        return "123";
    }
}
